//
//  SettingUserMessageViewController.m
//  much
//
//  Created by Believer Just on 2019/1/9.
//  Copyright © 2019年 iOS. All rights reserved.
//

#import "SettingUserMessageViewController.h"
#import "SettingUserMessageHeaderView.h"
#import "SettingUserMessageTableViewCell.h"
#import "MyInformationTextFiledSheet.h"
#import "MyInformationTextViewSheet.h"
#import "AuthorCertificationCustomAddressActionSheet.h"
#import "AddressManagementViewController.h"
#import "PublicAlert.h"
#import "UIImage+Resize.h"
#import "UIImage+Additions.h"

@interface SettingUserMessageViewController () <UITableViewDelegate, UITableViewDataSource, MyInformationTextFieldSheetDelegate, MyInformationTextViewSheetDelegates, AuthorCertificationCustomAddressActionSheetDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate>

@property (nonatomic, copy) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *sectionArray;
@property (nonatomic, strong) NSMutableArray *cellArray;
@property (nonatomic, copy) SettingUserMessageHeaderView *headerView;
@property (nonatomic, copy) MyInformationTextFiledSheet *nickNameAlert;
@property (nonatomic, copy) MyInformationTextViewSheet *describeAlert;
@property (nonatomic, copy) AuthorCertificationCustomAddressActionSheet *addressAlert;
@property (nonatomic, strong) NSString *cacheFileSize;
/** 图片选择器 */
@property (nonatomic, strong) UIImagePickerController *imagePicker;

@property (nonatomic, strong) NSString *avatarImagePathString;
@property (nonatomic, strong) NSString *nickNameString;
@property (nonatomic, strong) NSString *signatureString;
@property (nonatomic, strong) NSString *areaNameString;

@property (nonatomic, strong) UIButton *loginOutButton;

@end

@implementation SettingUserMessageViewController

- (void)_reLayout {
    self.navigationView.title = @"个人信息";
    [self initDataSource];
    
    [self setDescribeWithType:SettingUserMTVCSectionTypeFirst cellTag:SettingUserMTVCTypeNickname describe:USER.userBaseInfo.infoModel.nickname];
    [self setDescribeWithType:SettingUserMTVCSectionTypeFirst cellTag:SettingUserMTVCTypeIntroduce describe:USER.userBaseInfo.infoModel.signature];
    [self setDescribeWithType:SettingUserMTVCSectionTypeFirst cellTag:SettingUserMTVCTypeArea describe:USER.userBaseInfo.infoModel.areaName];
    [self setDescribeWithType:SettingUserMTVCSectionTypeThird cellTag:SettingUserMTVCTypeClearTheCache describe:self.cacheFileSize];
    [self setDescribeWithType:SettingUserMTVCSectionTypeThird cellTag:SettingUserMTVCTypeTheCurrentVersion describe:APP.applicationVersion];
}
- (void)popViewController {
    [self editValueHTTP];
}
- (void)initDataSource {
    self.avatarImagePathString = [[NSString alloc] init];
    self.nickNameString = [[NSString alloc] init];
    self.signatureString = [[NSString alloc] init];
    self.areaNameString = [[NSString alloc] init];
}


#pragma mark - method
/** 修改数据接口 */
- (void)editValueHTTP {
    if (self.nickNameString.hasValue || self.signatureString.hasValue || self.areaNameString.hasValue || self.avatarImagePathString.hasValue) {
        [MuchUserRequestManager editUserBaseMessage:self.nickNameString
                                      signature:self.signatureString
                                       areaName:self.areaNameString
                                        areaSid:USER.userBaseInfo.infoModel.areaSid
                                avatarImagePath:self.avatarImagePathString
                                 avatarImageSid:USER.userBaseInfo.infoModel.avatarImageSid
                                   successBlock:^(id  _Nonnull responseObject) {
                                       [self.navigationController popViewControllerAnimated:YES];
                                   } failureBlock:^(NSString *error) {
                                       [self.navigationController popViewControllerAnimated:YES];
                                   }];
    } else {
        [self.navigationController popViewControllerAnimated:YES];
    }
}
/** 修改数据 */
- (void)setDescribeWithType:(SettingUserMTVCSectionType)type cellTag:(SettingUserMTVCType)cellTag describe:(NSString *)describe  {
    NSMutableArray *array = [[NSMutableArray alloc] initWithArray:(NSArray *)self.sectionArray[type]];
    [array enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj[CellTag] integerValue] == cellTag) {
            NSString *describeString = [NSString backDefaultIfNilWithString:describe defaultString:@""];
            [obj setObject:describeString forKey:CellDecribe];
            *stop = YES;
        }
    }];
    [self.sectionArray setObject:array atIndexedSubscript:type];
    [self.tableView reloadData];
}
/** 修改昵称 */
- (void)editNickName {
    TYAlertController *alertController = [TYAlertController alertControllerWithAlertView:self.nickNameAlert preferredStyle:TYAlertControllerStyleActionSheet];
    alertController.backgoundTapDismissEnable = YES;
    [self presentViewController:alertController animated:YES completion:nil];
}
/** 修改介绍 */
- (void)editDescribe {
    TYAlertController *alertController = [TYAlertController alertControllerWithAlertView:self.describeAlert preferredStyle:TYAlertControllerStyleActionSheet];
    alertController.backgoundTapDismissEnable = YES;
    [self presentViewController:alertController animated:YES completion:nil];
}
/** 修改区域 */
- (void)editArea {
    TYAlertController *alertController = [TYAlertController alertControllerWithAlertView:self.addressAlert preferredStyle:TYAlertControllerStyleActionSheet];
    alertController.backgoundTapDismissEnable = YES;
    [self presentViewController:alertController animated:YES completion:nil];
}
/** 地址管理 */
- (void)editAddrManagement {
    AddressManagementViewController *vc = [[AddressManagementViewController alloc] initWithAddressManagementType:AddressManagementTypeNormal];
    [self.navigationController pushViewController:vc animated:YES];
}
/** 清除缓存 */
- (void)editClearTheCache:(NSIndexPath *)indexPath {
    NSString *libraryPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *cookiesFolderPath = [libraryPath stringByAppendingString:@"/Cookies"];
    NSError *errors;
    [[NSFileManager defaultManager] removeItemAtPath:cookiesFolderPath error:&errors];
    [[SDImageCache sharedImageCache] clearMemory];
    [[SDImageCache sharedImageCache] clearDiskOnCompletion:^{
        [SVProgressHUD showSuccessWithStatus:@"清理完成"];
        [self setDescribeWithType:SettingUserMTVCSectionTypeThird cellTag:SettingUserMTVCTypeClearTheCache describe:self.cacheFileSize];
        [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
    }];
}
/** 修改用户头像 */
- (void)editUserHeaderImage {
    [PublicAlert publicSimpleAlertController:self Title:@"图像选择" Message:@"相册或相机" Style:UIAlertControllerStyleActionSheet CancelActionTitle:@"相册" SureActionTitle:@"相机" DeleteActionTitle:@"取消" CancelActions:^(__autoreleasing id *result) {
        // 获取相册
        [self getAlbum];
    } SureActions:^(__autoreleasing id *result) {
        // 获取相机
        [self getCamera];
    } DeleteActions:^(__autoreleasing id *resutl) {
        
    }];
}
/** 获取相机 */
- (void)getCamera {
    NSArray *medioTypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];
    
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        self.imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
        self.imagePicker.mediaTypes = @[medioTypes[0]];
        self.imagePicker.cameraCaptureMode = UIImagePickerControllerCameraCaptureModePhoto;
        self.imagePicker.cameraDevice = UIImagePickerControllerCameraDeviceRear;
        self.imagePicker.cameraFlashMode = UIImagePickerControllerCameraFlashModeAuto;
        [self presentViewController:self.imagePicker animated:YES completion:nil];
    } else {
        NSLog(@"当前设置不支持摄像机！");
    }
}
/** 获取相册 */
- (void)getAlbum {
    NSArray *medioTypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
    
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
        self.imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        
        self.imagePicker.mediaTypes = @[medioTypes[0]];
        [self presentViewController:self.imagePicker animated:YES completion:nil];
    }
}
- (void)progressLoginOut {
    [USER logout:^(id  _Nonnull success) {}];
}


#pragma mark - <MyInformationTextFieldSheetDelegate>
/** 修改昵称 */
- (void)myInformationTextFieldSheetString:(NSString *)textfiledString {
    USER.userBaseInfo.infoModel.nickname = textfiledString;
    self.nickNameString = USER.userBaseInfo.infoModel.nickname;
    [self setDescribeWithType:SettingUserMTVCSectionTypeFirst cellTag:SettingUserMTVCTypeNickname describe:self.nickNameString];
}


#pragma mark - <MyInformationTextViewSheetDelegates>
/** 修改介绍 */
- (void)myInforMationTextViewSheetString:(NSString *)textViewString {
    USER.userBaseInfo.infoModel.signature = textViewString;
    self.signatureString = USER.userBaseInfo.infoModel.signature;
    [self setDescribeWithType:SettingUserMTVCSectionTypeFirst cellTag:SettingUserMTVCTypeIntroduce describe:self.signatureString];
}


#pragma mark - <AuthorCertificationCustomAddressActionSheetDelegate>
/** 修改地址 */
- (void)getAuthorCertificationCustomAddressActionSheetString:(NSString *)addressASString areaSid:(NSString *)areaSid {
    USER.userBaseInfo.infoModel.areaName = addressASString;
    USER.userBaseInfo.infoModel.areaSid = areaSid;
    self.areaNameString = USER.userBaseInfo.infoModel.areaName;
    [self setDescribeWithType:SettingUserMTVCSectionTypeFirst cellTag:SettingUserMTVCTypeArea describe:self.areaNameString];
}


#pragma mark - <UIImagePickerControllerDelegate>
/** 当用户完成某个图片或视频的选取 */
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    UIImage *img = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
    img = [UIImage rotateImage:img];
    img = [img resizeImageGreaterThan:kMaxResolution];
    
    CoverViewController *coverVC = [[CoverViewController alloc] initWithImage:img delegate:self];
    [picker pushViewController:coverVC animated:YES];
}
#pragma mark - <CoverViewControllerDelegate>
- (void)coverViewControllerDidFinishWithImage:(UIImage *)image {
    NSData *avatarData = UIImageJPEGRepresentation(image, .5f);

    [MuchHttpRequestManager uploadImageRequestWithAPI:UploadImageTypeUserAvatar imageKey:@"file" imageData:avatarData success:^(id  _Nonnull responseObject) {
        [SVProgressHUD showSuccessWithStatus:@"上传成功！"];
        
        NSDictionary *dict = responseObject[0];
        ImageModel *model = [ImageModel modelWithDictionary:dict];
        USER.userBaseInfo.infoModel.avatarImagePath = model.path;
        USER.userBaseInfo.infoModel.avatarImageSid = model.sid;
        self.avatarImagePathString = USER.userBaseInfo.infoModel.avatarImagePath;
        self.headerView.uploadUserHeaderImage = YES;
    } failure:^(NSString *error) {
        [SVProgressHUD showErrorWithStatus:error];
    }];
}


#pragma mark - <UITableViewDelegate, UITableViewDataSource>
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.sectionArray.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.sectionArray[section] count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SettingUserMessageTableViewCell *cell = [SettingUserMessageTableViewCell initTableView:tableView];
    return cell;
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    SettingUserMessageTableViewCell *userCenterHomeTableViewCell = (SettingUserMessageTableViewCell *)cell;
    userCenterHomeTableViewCell.dic = self.sectionArray[indexPath.section][indexPath.row];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    switch ([self.sectionArray[indexPath.section][indexPath.row][CellTag] integerValue]) {
        case SettingUserMTVCTypeNickname:
            [self editNickName];
            break;
        case SettingUserMTVCTypeIntroduce:
            [self editDescribe];
            break;
        case SettingUserMTVCTypeArea:
            [self editArea];
            break;
        case SettingUserMTVCTypeAddrManagement:
            [self editAddrManagement];
            break;
        case SettingUserMTVCTypeClearTheCache:
            [self editClearTheCache:indexPath];
            break;
        case SettingUserMTVCTypeTheCurrentVersion:
            
            break;
        default:
            break;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat normalHeight = 44.f;
    return normalHeight;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 10.f;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.001f;
}


#pragma mark - 懒加载
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.backgroundColor = Color244;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.separatorStyle = UITableViewCellAccessoryNone;
        _tableView.tableHeaderView = self.headerView;
        [self.view addSubview:_tableView];
        [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.navigationView.mas_bottom);
            make.left.and.right.equalTo(self.view);
            make.bottom.equalTo(self.loginOutButton.mas_top);
        }];
    }
    return _tableView;
}
- (UIButton *)loginOutButton {
    if (!_loginOutButton) {
        _loginOutButton = [UIButton buttonWithType:UIButtonTypeSystem];
        _loginOutButton.backgroundColor = Color175030;
        [_loginOutButton setTitle:@"退出登录" forState:UIControlStateNormal];
        [_loginOutButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_loginOutButton.titleLabel setFont:APPFONT(15)];
        [_loginOutButton addTarget:self action:@selector(progressLoginOut) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:_loginOutButton];
        [_loginOutButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.and.bottom.and.right.equalTo(self.view);
            make.height.mas_equalTo(49);
        }];
    }
    return _loginOutButton;
}
- (SettingUserMessageHeaderView *)headerView {
    if (!_headerView) {
        _headerView = [[SettingUserMessageHeaderView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 143)];
        
        __weakConfigure
        _headerView.settingUserMessageHVBlock = ^{
            [__weakSelf editUserHeaderImage];
        };
    }
    return _headerView;
}
- (NSMutableArray *)sectionArray {
    if (!_sectionArray) {
        _sectionArray = [[NSMutableArray alloc] init];
        NSMutableDictionary *dic;
        
        NSMutableArray *firstCellArray = [[NSMutableArray alloc] init];
        dic = [[NSMutableDictionary alloc] initWithDictionary:@{CellTitle:@"昵称", CellDecribe:@"", CellTag:@(SettingUserMTVCTypeNickname), CellShowLine:@(YES)}];
        [firstCellArray addObject:dic];
        dic = [[NSMutableDictionary alloc] initWithDictionary:@{CellTitle:@"介绍", CellDecribe:@"", CellTag:@(SettingUserMTVCTypeIntroduce), CellShowLine:@(YES)}];
        [firstCellArray addObject:dic];
        dic = [[NSMutableDictionary alloc] initWithDictionary:@{CellTitle:@"区域", CellDecribe:@"", CellTag:@(SettingUserMTVCTypeArea), CellShowLine:@(NO)}];
        [firstCellArray addObject:dic];
        [_sectionArray addObject:firstCellArray];
        
        NSMutableArray *secondCellArray = [[NSMutableArray alloc] init];
        dic = [[NSMutableDictionary alloc] initWithDictionary:@{CellTitle:@"地址管理", CellDecribe:@"", CellTag:@(SettingUserMTVCTypeAddrManagement), CellShowLine:@(NO)}];
        [secondCellArray addObject:dic];
        [_sectionArray addObject:secondCellArray];
        
        NSMutableArray *thirdCellArray = [[NSMutableArray alloc] init];
        dic = [[NSMutableDictionary alloc] initWithDictionary:@{CellTitle:@"清理缓存", CellDecribe:@"", CellTag:@(SettingUserMTVCTypeClearTheCache), CellShowLine:@(YES)}];
        [thirdCellArray addObject:dic];
        dic = [[NSMutableDictionary alloc] initWithDictionary:@{CellTitle:@"当前版本", CellDecribe:@"", CellTag:@(SettingUserMTVCTypeTheCurrentVersion), CellShowLine:@(NO)}];
        [thirdCellArray addObject:dic];
        [_sectionArray addObject:thirdCellArray];
    }
    return _sectionArray;
}
- (MyInformationTextFiledSheet *)nickNameAlert {
    if (!_nickNameAlert) {
        _nickNameAlert = [[MyInformationTextFiledSheet alloc] initWithFrame:self.view.frame];
        _nickNameAlert.delegate = self;
        _nickNameAlert.textfieldAlreadyString = USER.userBaseInfo.infoModel.nickname;
    }
    return _nickNameAlert;
}
- (MyInformationTextViewSheet *)describeAlert {
    if (!_describeAlert) {
        _describeAlert = [[MyInformationTextViewSheet alloc] initWithFrame:self.view.frame];
        _describeAlert.delegate = self;
        _describeAlert.placeholder = @"请输入介绍";
        _describeAlert.textViewAlreadyString = USER.userBaseInfo.infoModel.signature;
    }
    return _describeAlert;
}
- (AuthorCertificationCustomAddressActionSheet *)addressAlert {
    if (!_addressAlert) {
        _addressAlert = [[AuthorCertificationCustomAddressActionSheet alloc] initWithFrame:self.view.frame];
        _addressAlert.delegate = self;
        _addressAlert.isContainsDistrict = YES;
    }
    return _addressAlert;
}
- (UIImagePickerController *)imagePicker {
    if (!_imagePicker) {
        _imagePicker = [[UIImagePickerController alloc] init];
        _imagePicker.delegate = self;
    }
    return _imagePicker;
}


- (NSString *)cacheFileSize {
    NSUInteger k = 1024,
    m = 1024 * k,
    g = 1024 * m,
    size = [[SDImageCache sharedImageCache] getSize];
    if(size < k) {
        return [NSString stringWithFormat:@"%luB", (unsigned long)size];
    }
    else if(size < m) {
        return [NSString stringWithFormat:@"%.1fK", (float)(size / k)];
    }
    else if(size < g) {
        return [NSString stringWithFormat:@"%.1fM", (float)(size / m)];
    }
    else {
        return [NSString stringWithFormat:@"%.1fG", (float)(size / g)];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

@end
